package com.macro.mall.util;

import cn.hutool.core.net.URLDecoder;
import cn.hutool.json.JSONObject;
import org.springframework.core.MethodParameter;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import javax.servlet.http.HttpServletRequest;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;

/**
 * 解析requestData
 */
public class RequestDataMethodArgumentResolver implements HandlerMethodArgumentResolver {

    private static final String DEFAULT_ENC = "UTF-8";

    @Override
    public boolean supportsParameter(MethodParameter methodParameter) {
        return methodParameter.hasParameterAnnotation(RequestData.class);
    }

    @Override
    public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
                                  NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
        String json = parseParameters(webRequest);
        if (StringUtils.isEmpty(json)) {
            return null;
        }
        return new JSONObject(json).toBean(parameter.getGenericParameterType());
    }

    /**
     * 解析request
     * 1.请求是get，入参d=,将d解析成对应的bean
     * 2.请求是get，入参是json，将参数转换成对应的bean
     * 3.请求是post，body是json，将参数转换成对应的bean
     *
     * @return json
     */
    protected String parseParameters(NativeWebRequest nativeRequest) throws IOException {
        HttpServletRequest servletRequest = nativeRequest.getNativeRequest(HttpServletRequest.class);
        String method = servletRequest.getMethod();

        if ("GET".equals(method) || "DELETE".equals(method)) {
            return getQueryString(servletRequest);
        }

        StringBuilder jsonstr = new StringBuilder();
        String line;
        BufferedReader br = servletRequest.getReader();

        while ((line = br.readLine()) != null) {
            jsonstr.append(line);
        }

        String str = jsonstr.toString();

        if (StringUtils.isEmpty(str)) {
            return null;
        }
        return str;
    }

    /**
     * 解析get请求参数
     *
     * @return json
     */
    protected String getQueryString(HttpServletRequest request) {
        String queryStr = request.getQueryString();
        if (StringUtils.isEmpty(queryStr)) {
            return null;
        }

        String decodedStr = URLDecoder.decode(queryStr, Charset.defaultCharset());
        if (StringUtils.hasText(decodedStr)) {
            decodedStr = URLDecoder.decode(queryStr, Charset.defaultCharset());
            if (StringUtils.hasText(decodedStr)) {
                StringBuffer sb = new StringBuffer("{");
                String[] parameters = decodedStr.split("&");
                if (parameters.length > 0) {
                    for (int i = 0; i < parameters.length; i++) {
                        String[] parameter = parameters[i].split("=");
                        if (parameter.length == 2) {
                            String objectEscape = parameter[1].startsWith("[") || parameter[1].startsWith("{") ? "" : "\"";
                            sb.append("\"").append(parameter[0]).append("\":").append(objectEscape)
                                    .append(parameter[1]).append(objectEscape).append(i == parameters.length - 1 ? "" : ",");
                        }
                    }
                }
                sb.append("}");
                return sb.toString();
            }
        }

        return null;
    }
}
